﻿// description  : 用户认证
// author       : tristan
// created      : 2011/2/16
// contact      : snaprack@gmail.com

namespace RBAC
{
    using System.Linq;

    /// <summary>
    /// 用户认证服务
    /// </summary>
    public class Authentication
    {
        string _account;
        /// <summary>
        /// 设置服务对象账户
        /// </summary>
        /// <param name="accountID">账户ID</param>
        public void SetAccount(string accountID)
        {
            _account = accountID;
        }

        /// <summary>
        /// 获取和设置认证用户
        /// </summary>
        /// <summary>
        /// 登入
        /// </summary>
        /// <param name="user">用户</param>
        /// <param name="password">密码</param>
        /// <return>
        ///     <list>
        ///         <item>1:成功</item>
        ///         <item>-1:用户不存在</item>
        ///         <item>-2:密码不正确</item>
        ///     </list>
        /// </return>
        public int Signin(string password)
        {
            Account account = Account.Load(this._account);

            if (account == null)                        return -1;
            if (!account.Password.Equals(password))     return -2;

            return 1;
        }

        /// <summary>
        /// 更改密码
        /// </summary>
        /// <param name="current">当前密码</param>
        /// <param name="replace">新密码</param>
        /// <returns>
        ///     <list>
        ///         <item>1:成功</item>
        ///         <item>-1:用户不存在</item>
        ///         <item>-2:当前密码不正确</item>
        ///     </list>
        /// </returns>
        public int ChangePassword(string current, string replace)
        {
            Account account = Account.Load(_account);

            if (account == null)                        return -1;
            if (!current.Equals(account.Password))      return -2;

            account.Password = replace;
            account.Save();

            return 1;
        }

        public void ResetPassword()
        {
            Account account = Account.Load(_account);
            account.Password = Account.DefaultPassword;
            account.Save();
        }

        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="password">密码</param>
        public void Register(string password)
        {
            Account account = new Account { ID = _account, Password = password };
            account.Add();
            account.Save();
        }

        /// <summary>
        /// 注销用户
        /// </summary>
        public void Unregister()
        {
            Account account = Account.Load(_account);
            account.Remove();
            account.Save();
        }
    }

}
